package cn.cqautotest.downloadfile.download

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Environment
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import cn.cqautotest.downloadfile.R
import cn.cqautotest.downloadfile.expand.toFileSize
import java.io.File
import java.text.DecimalFormat

/**
 * 文件下载后台服务
 */
@RequiresApi(Build.VERSION_CODES.O)
class DownloadFileService : Service(), DownloadFileListener {

    // lateinit var 关键字用于声明延迟初始化变量，使用该变量前必须确保变量已经初始化
    // 可使用 ::notificationBuilder.isInitialized 这种方式判断该变量是否已经初始化
    private lateinit var notificationBuilder: Notification.Builder
    private lateinit var manager: NotificationManager
    private lateinit var appContext: Context
    private var isDownloading = false

    override fun onCreate() {
        super.onCreate()
        appContext = applicationContext
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        var downloadPath: String
        // Environment.DIRECTORY_DOWNLOADS 这个目录不需要申请存储权限，即使是 Android 11
        getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).run {
            downloadPath = this?.path.toString()
            // 如果此字符串为空或仅由空格字符组成，则返回 true
            // 调用 isBlank() 函数等同于 downloadPath == null || downloadPath.length == 0 || downloadPath.trim().length == 0
            if (downloadPath.isBlank()) downloadPath = cacheDir.path
        }
        DownloadFileRequest.download(BASE_URL + SUFFIX_URL, downloadPath, "氢流.apk", this)
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBeforeBegin(file: File, fileIsExists: Boolean): Boolean {
        Log.d(TAG, "onBeforeBegin: ===> DownloadFilePath：${file.path}")
        Log.d(
            TAG,
            "onStarted: ====> 文件状态：${if (fileIsExists) "存在 取消下载..." else "不存在 准备开始下载..."} "
        )
        showNotify()
        // return fileIsExists.not()
        return true
    }

    override fun onProgressChanged(
        currentLength: Long,
        totalLength: Long,
        downloadUrl: String
    ) {
        isDownloading = true
        // 注意：这里计算出来的是读取文件流的进度，不是实际的下载进度
        val progress =
            ((DecimalFormat("0.00").format(currentLength / (totalLength * 1.0))).toFloat() * 100).toInt()
        Log.d(
            TAG,
            "onProgressChanged: ====> ${progress}% 已下载文件大小：${currentLength.toFileSize()}总文件大小：${totalLength.toFileSize()}"
        )
        notificationBuilder.run {
            setProgress(100, progress, false)
            setContentText("进度：${DecimalFormat("0.00%").format((currentLength * 1.0) / (totalLength * 1.0))}")
        }
        // 发布要在状态栏中显示的通知。如果您的应用程序已经发布了具有相同ID的通知，但尚未取消，则该通知将由更新的信息代替。
        manager.notify(1, notificationBuilder.build())
    }

    override fun onFinished(completeSize: Long, downloadUrl: String, file: File) {
        isDownloading = false
        Log.d(TAG, "onFinished: ====> 文件总长度：${completeSize.toFileSize()}")
        Toast.makeText(appContext, "文件下载完成！", Toast.LENGTH_SHORT).show()
    }

    override fun onFailure(file: File, t: Throwable?) {
        isDownloading = false
        // 下载失败，删除这个文件
        file.delete()
        Log.d(TAG, "onFailure: ====> 文件下载失败...")
        Toast.makeText(appContext, "文件下载失败！", Toast.LENGTH_SHORT).show()
    }

    //展示通知 成为前台服务
    private fun showNotify() {
        createChannel()
        notificationBuilder =
            Notification.Builder(this, "1").apply {
                // 设置自动取消
                setAutoCancel(false)
                // 设置通知的标题
                setContentTitle(getString(R.string.app_name))
                // 设置通知的内容
                setContentText("运行中...")
                // 添加与通知相关的时间戳(通常是事件发生的时间)，简单来说就是描述你什么时候发的通知的
                setWhen(System.currentTimeMillis())
                // 如果不设置为 true 则不显示上面那个
                setShowWhen(true)
                // 设置小图标
                setSmallIcon(R.mipmap.ic_launcher_round)
                // 设置大图标
                setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
                // 设置进度值
                setProgress(100, 0, false)
            }
        // 将当前 Service 变成前台 Service
        startForeground(1, notificationBuilder.build())
    }

    //创建channel
    private fun createChannel() {
        manager = getSystemService(NotificationManager::class.java)
        val channel = NotificationChannel(
            "1",
            getString(R.string.app_name),
            NotificationManager.IMPORTANCE_LOW
        )
        channel.lockscreenVisibility = Notification.VISIBILITY_SECRET
        // 创建通知渠道
        manager.createNotificationChannel(channel)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: ===> Service 结束了！")
    }

    companion object {
        private const val TAG = "UpdateAppService"
        const val BASE_URL = "https://fga1.market.xiaomi.com/"

        // const val SUFFIX_URL =
        //     "download/AppStore/069475966fd89af02f12cc4bee5e806548b41a35b/com.lbe.parallel.apk"
        const val SUFFIX_URL =
            "download/AppStore/0633bb5eed249493201c30f8c47ed685da20fe05b/com.qingliu.browser.apk"
    }
}